import { getUserInfoAPI, loginAPI } from '@/api/user'
import router, { constantRoutes, resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  userInfo: {},
  // 定义路由数据
  routes: constantRoutes
}

const mutations = {
  saveToken(state, playload) {
    state.token = playload
  },
  saveUserInfo(state, playload) {
    state.userInfo = playload
  },
  // 定义mutations函数，用于更新路由数据
  setRoutes(state, playload) {
    state.routes = [...constantRoutes, ...playload]
  }
}

const actions = {
  async loginAction(state, playload) {
    const res = await loginAPI(playload)
    // 将从API响应中获取的token保存到Vuex状态中
    state.commit('saveToken', res)
    // 将token保存到本地存储中，以便后续使用
    setToken(res)
    router.push('/')

    Message({
      message: '登录成功',
      type: 'success'
    })
  },
  async getUserInfoAction(state) {
    const res = await getUserInfoAPI()
    state.commit('saveUserInfo', res)
  },

  // 1. 封装退出的action
  logoutAction(store) {
    store.commit('saveToken', '') // 清空vuex中token
    removeToken() // 清空cookie中的token
    store.commit('saveUserInfo', {}) // 清空vuex中userInfo
    router.push('/login') // 跳转到登录
    resetRouter() // 重置路由
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

